/*
 * @author Javier A. Ramírez M.
 * jaramirez85@yahoo.es
 */

package com.jav;

import com.jav.inter.Constantes;
import com.jav.per.PersisPedido;
import com.jav.per.Persistencia;
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.TabbedPane;
import com.sun.lwuit.animations.Transition3D;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.util.Resources;
import java.util.Hashtable;
import javax.microedition.rms.RecordEnumeration;


public class ReportForm extends Form implements Constantes{
    
    private TabbedPane tab = new TabbedPane();
    private Button bt_numPed = createButton();
    private Button bt_valPed = createButton();
    private Button bt_valCam = createButton();
    private Button bt_porce = createButton();

    public ReportForm() {
        super("INFORMES");
        setLayout(new BorderLayout());
        try {
            setTransitionInAnimator(Transition3D.createSwingIn(500));
            setTransitionOutAnimator(Transition3D.createSwingIn(500, false));
            Resources res = Datos.getInstance().getRes();
            Container ct1 = new Container(new BoxLayout(BoxLayout.Y_AXIS));
            Container ct2 = new Container(new BoxLayout(BoxLayout.X_AXIS));
            ct1.addComponent(createPair("$ peds", bt_valPed, 20));
            ct1.addComponent(createPair("$ camb", bt_valCam, 20));
            ct2.addComponent(createPair("#P", bt_numPed, 15));
            ct2.addComponent(createPair("%C", bt_porce, 15));
            ct1.addComponent(ct2);
            

            tab.addTab("TOTAL VENTAS", ct1);
            tab.addTab("EFECTIVIDAD", new EfectividadContainer());
            tab.addTab("PROVEEDOR", new ProveedorContainer());
            tab.addTab("TABLA", new VentasXClientesContainer());
            addComponent("Center", tab);
            
            addCommand(new Command("Atrás", res.getImage("bck.png")) {

                public void actionPerformed(ActionEvent evt) {
                    CapMovil.getMainForm().show();
                }
            });
            
            addCommand(new Command("Next", res.getImage("playtrack.png")) {

                public void actionPerformed(ActionEvent evt) {
                    int i = tab.getSelectedIndex();
                    if (i == 3) {
                        i = 0;
                    } else {
                        i++;
                    }
                    tab.setSelectedIndex(i);
                }
            });
            cargaDatosTotVentas();
            
        } catch (Exception e) {
            Datos.getInstance().getLogs().append(e.getMessage());
        }
    }
    
    protected Container createPair(String label, Component c, int minWidth) {
        Container pair = new Container(new BorderLayout());
        Label l =  new Label(label);
        Dimension d = l.getPreferredSize();
        d.setWidth(Math.max(d.getWidth(), minWidth));
        l.setPreferredSize(d);
        l.getStyle().setBgTransparency(100);
        pair.addComponent(BorderLayout.WEST,l);
        pair.addComponent(BorderLayout.CENTER, c);
        return pair;
    }

    private void cargaDatosTotVentas() {
        Hashtable ht = getInfoPedidos();
        if(ht != null && ht.size() > 0){            
            bt_numPed.setText((String) ht.get("cantidad"));
            bt_valPed.setText("$ "+(String) ht.get("totPedido"));
            bt_valCam.setText("$ "+(String) ht.get("totCambio"));
            bt_porce.setText((String) ht.get("porcentaje"));
            repaint();
        }
        else{
            bt_numPed.setText("SIN DATOS");
            bt_valCam.setText("SIN DATOS");
            bt_valPed.setText("SIN DATOS");
        }

    }

    private Button createButton() {
        Button boton = new Button(""){

            public void startTicker(long delay, boolean rightToLeft) {
                super.startTicker(100, true);
            }

        };
        boton.getStyle().setBgColor(0xFF8C00);
        boton.getStyle().setFgColor(0x000000);
        boton.setAlignment(CENTER);
        return boton;
    }

    private Hashtable getInfoPedidos(){

        Persistencia p = null;
        Hashtable ht = new Hashtable();
        int ctr = 0;
        long totPedido=0;
        long totCambio=0;
        String porc ="";
        try {
            p = new Persistencia(PERS_PEDIDO);
            RecordEnumeration re = p.getRecordStore().enumerateRecords(null,null,false);
            while (re.hasNextElement()){
                ctr ++;
                PersisPedido pd = new PersisPedido();
                pd.resurrect(re.nextRecord());
                totPedido += pd.getVenta();
                totCambio += pd.getCambio();    
                if (totPedido != 0){
                    porc = getPorcentaje(totCambio,totPedido);
                }
                ht.put("porcentaje", porc);
                ht.put("cantidad", String.valueOf(ctr));
                ht.put("totPedido", String.valueOf(totPedido));
                ht.put("totCambio", String.valueOf(totCambio));                
            }

        }
        catch (Exception ex) {
                ex.printStackTrace();
        }
        finally{
            try {
                if(p != null){
                    p.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        return ht;

    }

    private String getPorcentaje(long n, long d){
        String resp = "0";
        try {
            float porc = 0;
            if (d != 0){
                porc = (new Float(n).floatValue()/new Float(d).floatValue())*100;
            }
            resp = String.valueOf(porc);
            resp = resp.length() > 2 ? resp.substring(0, 3):resp;
            
        }
        catch (Exception e) {
            resp = "NO SOPORTA PUNTO FLOTANTE";
        }
        return resp;


    }

}
